#include "sendfile.h"
extern QSemaphore sem_process;
sendfile::sendfile(QObject *parent) : QObject(parent)
{

}


void sendfile::setfilename(QString name)
{
    if(file.isOpen())
        file.close();
    filename=name;
    qDebug()<<tr("file name is %1").arg(name);
}

QString sendfile::getfilename()
{
    return filename;
}

bool sendfile::get_update_sta()
{
    unsigned char msg[100];
    int len=0;
    create_update_msg(msg,&len);
    QByteArray tmp;
    tmp.append((char*)msg,len);
    emit sendmsg(tmp);
    if(sem_process.tryAcquire(1,5000))
    {
        /*
         * 这里只是加入了有没有数据返回的判断，没有传递返回的数据
         *
         */
        //        if()
        //        {

//        emit dis_result(tr("respond sucessful"));
        //        }
        return true;
    }

    return false;
}

bool sendfile::upgrade_pack(QByteArray data, int pack_num, int current_pack_num, unsigned int version)
{
    unsigned char tmp[1024*5];
    memset(tmp,0,sizeof(tmp));
    int _len=0;
    foreach (auto val, data) {
        tmp[_len++]=val;
    }
    creat_upgrade_msg(
                tmp,
                &_len,
                pack_num,
                current_pack_num,
                version);
    QByteArray arraydata;
    arraydata.append((char*)tmp,_len);
    emit sendmsg(arraydata);
    if(sem_process.tryAcquire(1,5000))
    {
        /*
         * 加入对返回数据的处理函数，包括crc 转义，以及执行状态，
         *
         */
        return true;
    }


        return false;

}

void sendfile::upgrade_frameware()
{
    emit setProgress(0);
    bool sta=get_update_sta();
    if(sta==false)
    {
        emit err(tr("response err !"));
        return;
    }

    if(filename.isEmpty())
    {
        emit err(tr("file path is invalid!"));
        return;
    }
    qDebug()<<"file name:"<<filename;
    file.setFileName(filename);
    if(false==file.open(QIODevice::ReadOnly))
    {
        emit err(tr("open file:%1 fail!").arg(filename));
        return;
    }
    int len=(file.size()/1024)+(file.size()%1024?1:0);
    emit setProgressMax(len);
    qDebug()<<"file size:"<<file.size()<<"len:"<<len;
    for(int i=1;i<=len;i++)
    {
        QByteArray send_data=file.read(1024);

        if(false==upgrade_pack(send_data,len,i,version))
        {
            emit err(tr("send upgrade data pack fail"));
            return ;
        }
        emit setProgress(i);
    }

    emit err(tr("upgrade successful!"));
    return ;
}
